package com.vueapi.aspect;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.vueapi.annotation.OperationLog;
import com.vueapi.domain.HjOperationLog;
import com.vueapi.domain.VisitLog;
import com.vueapi.service.HjOperationLogService;
import com.vueapi.service.VisitLogService;
import com.vueapi.utils.HttpContextUtil;
import com.vueapi.utils.IPUtils;
import com.vueapi.utils.JwtUtil;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import net.dreamlu.mica.ip2region.core.IpInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @Classname LogBlogAspect
 * @Description TODO
 * @Created by 赵宏建
 * @Date 2022/9/20 14:29
 * @Version 1.0.0
 */
@Component
@Aspect
public class VisitLogAspect {

    @Autowired
    private Ip2regionSearcher ip2regionSearcher;

    @Resource
    VisitLogService visitLogService;

    @Pointcut("@annotation(com.vueapi.annotation.VisitLog)")
    public void operationLogPoint(){}

    @Around("operationLogPoint()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object result = pjp.proceed();
        recordLog(pjp);
        return result;
    }

    public void recordLog(ProceedingJoinPoint pjp){
        // 获取请求参数
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();


        VisitLog visitLog = new VisitLog();
        // 获取异常发生的操作IP
        String ip = IPUtils.getIpAddr(HttpContextUtil.getHttpServletRequest());
        IpInfo ipInfo = ip2regionSearcher.memorySearch(ip);
        String address = "UNKNOWN";
        if(ipInfo != null){
            address = ipInfo.getAddress();
        }

        visitLog.setId(IdUtil.fastUUID());
        visitLog.setIp(ip);
        visitLog.setIpSource(address);
        visitLogService.save(visitLog);
    }
}
